package com.gkr.shopping.serviceimpl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.gkr.shopping.bean.Order;
import com.gkr.shopping.bean.OrderItem;
import com.gkr.shopping.bean.User;
import com.gkr.shopping.mapper.OrderItemMapper;
import com.gkr.shopping.mapper.OrderMapper;
import com.gkr.shopping.service.OrderService;


@Service("orderService")
@Transactional
public class OrderServiceImpl implements OrderService {
	
	@Autowired
	private OrderMapper orderMapper;
	
	@Autowired
	private OrderItemMapper orderItemMapper;
	//提交订单
	@Override
	public Order orderSubmit(String orderInfo) {
		// TODO Auto-generated method stub
		//创建订单对象
		Order order = new Order();
		try {
			String[]  orderInfos = orderInfo.substring(1).split("#");

			order.setCreateDate(new Date());

			HttpSession session = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getSession();

			int userId = ((User)session.getAttribute("session_user")).getId();

			order.setUserId(userId);
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

			order.setOrderCode("PO-"+sdf.format(new Date())+userId);

			double totalPrice = 0.0;
			
			//创建集合用于封装订单详情信息
			List<OrderItem> items = new ArrayList<>();
			for(String  info: orderInfos) {
				String[] infos =info.split("_");
				
				//获取商品id
				int articleId = Integer.valueOf(infos[0]);
				//购买数量
				int buyNum = Integer.valueOf(infos[1]);
				
				OrderItem item = new OrderItem();
				item.setArticleId(articleId);
				item.setOrderNum(buyNum);
				
				//订单详细记录放在集合中
				items.add(item);
				
				totalPrice += Double.valueOf(infos[2]);
			}

			order.setAmount(totalPrice);

			orderMapper.saveOrder(order);

			int orderId = order.getId();
			for(OrderItem item : items) {
				item.setOrderId(orderId);
				//保存订单明细
				orderItemMapper.saveItem(item);
			}	
		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}	

       return order;
		
	}
	
	//根据当前用户的id查询，该用户所有的订单信息
	@Override
	public List<Order> getOrdersByUserId() {
		// TODO Auto-generated method stub

		HttpSession session = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getSession();

		int userId = ((User)session.getAttribute("session_user")).getId();
	
		return orderMapper.getOrdersByUserId(userId);
	}

	@Override
	public void updateOrderPayOrderNo(String orderNo) {
		// TODO Auto-generated method stub
		orderMapper.updateOrderPayOrderNo(orderNo);
	}
	
}
